package com.base.cn.platform.os.controller.classes.member;

import com.base.cn.platform.os.common.controller.BaseController;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.entity.classes.Classes;
import com.base.cn.platform.os.entity.classes.condition.ClassesMemberCondition;
import com.base.cn.platform.os.entity.classes.member.ClassesMember;
import com.base.cn.platform.os.entity.course.cou.Course;
import com.base.cn.platform.os.entity.course.cou.buy.CourseBuyRecord;
import com.base.cn.platform.os.service.classes.ClassesBiz;
import com.base.cn.platform.os.service.classes.member.ClassesMemberBiz;
import com.base.cn.platform.os.service.classes.topic.ClassesTopicBiz;
import com.base.cn.platform.os.service.course.cou.CourseBiz;
import com.base.cn.platform.os.service.course.cou.buy.CourseBuyRecordBiz;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 班级成员
 *
 * @author SK
 * @since 2018-05-10
 */
@RestController
@RequestMapping("/course")
public class ClassesMemberController extends BaseController {

    @Autowired
    private ClassesBiz classesBiz;
    @Autowired
    private ClassesMemberBiz classesMemberBiz;
    @Autowired
    private ClassesTopicBiz classesTopicBiz;
    @Autowired
    private CourseBuyRecordBiz courseBuyRecordBiz;
    @Autowired
    private CourseBiz CourseBiz;


    /**
     * 班级成员个人信息统计
     *
     * @param userId 前台用户id
     * @return 个人信息统计
     */
    @RequestMapping("/classesMemberStatistics")
    public Map<String, Object> classesMemberStatistics(@RequestParam("userId") BigDecimal userId) {
        Map<String, Object> statistics = new HashMap<>();
        //查询用户加入的班级数量
        BigDecimal classesCount = classesMemberBiz.countMemberClasses(userId);
        statistics.put("classesCount", classesCount);
        //我的话题统计（发表话题量，参与回复的话题量）
        Map<String, Object> data = classesTopicBiz.classesPersonalTopicStatistics(userId);
        statistics.putAll(data);
        return statistics;
    }

    /**
     * 查询班级成功
     * @param condition 查询条件
     * @return Map<BigDecimal,List<ClassesMember>> 班级ID为Key
     */
    @RequestMapping("/findClassesMemberListMap")
    public Map<BigDecimal,List<ClassesMember>> findClassesMemberListMap(@RequestBody ClassesMemberCondition condition){
        List<ClassesMember> classesMemberList = classesMemberBiz.findClassesMemberList(condition, false);
        if(ObjectUtils.isNotEmpty(classesMemberList)){
            return classesMemberList.stream().collect(Collectors.groupingBy(e->e.getClassesId()));
        }
        return null;
    }

    /**
     * 查询班级成员
     *
     * @param condition 查询条件
     * @param setMember 设置班级成员
     * @param order     排序 1.班主任 -> 管理学员
     * @param identity  1.普通学员 2.班级管理员 3.班主任
     * @return 班级成员
     */
    @RequestMapping("/findClassesMemberList")
    public List<ClassesMember> findClassesMemberList(@RequestBody ClassesMemberCondition condition,
                                                     @RequestParam("setMember") boolean setMember,
                                                     @RequestParam(value = "order", required = false) Integer order,
                                                     @RequestParam(value = "identity", required = false) int... identity) {
        condition.setIdentities(identity);
        condition.setOrder(order);
        return classesMemberBiz.findClassesMemberList(condition, setMember);
    }

    /**
     * 查询班级成员
     *
     * @param condition   查询条件
     * @param currentPage 当前页
     * @param pageSize    每页数据量
     * @param setMember   设置班级成员
     * @param order       排序 1.班主任 -> 管理学员
     * @param identity    1.普通学员 2.班级管理员 3.班主任
     * @return 班级成员
     */
    @RequestMapping("/findClassesMemberPage")
    public PageInfo<ClassesMember> findClassesMemberPage(@RequestBody ClassesMemberCondition condition,
                                                         @RequestParam(value = "currentPage", required = false, defaultValue = "1") Integer currentPage,
                                                         @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                                         @RequestParam("setMember") boolean setMember,
                                                         @RequestParam(value = "order", required = false) Integer order,
                                                         @RequestParam(value = "identity", required = false) int... identity) {
        Pagination pagination = new Pagination();
        pagination.setCurrentPage(currentPage);
        if (DataUtil.isPositive(pageSize)) {
            pagination.setPageSize(pageSize);
        }
        condition.setIdentities(identity);
        condition.setOrder(order);
        return classesMemberBiz.findClassesMemberPage(condition, pagination, setMember);
    }

    /**
     * 是否加入班级
     *
     * @param classesId 班级id
     * @param memberId  班级成员的id
     * @return {@code true}加入，否则返回{@code false}
     */
    @RequestMapping("/joined")
    public boolean joined(@RequestParam("classesId") BigDecimal classesId,
                          @RequestParam("memberId") BigDecimal memberId) {
        return classesMemberBiz.isJoined(classesId, memberId);
    }

    /**
     * 保存班级成员
     *
     * @param classesId 班级id
     * @param memberIds 成员id(对应用户id)
     * @param identity  1.普通学员 2.班级管理员 3.班主任
     * @param source    1.前台(APP H5 WEB 小程序) 2.后台
     * @return 保存结果
     */
    @RequestMapping("/saveClassesMemberBatch")
    public Map<String, Object> saveClassesMemberBatch(@RequestParam("classesId") BigDecimal classesId,
                                                      @RequestParam("memberIds") String memberIds,
                                                      @RequestParam("identity") Integer identity,
                                                      @RequestParam("source") Integer source) {
        Map<String, Object> check = this.checkRequestParams(classesId, memberIds);
        if (check != null) {
            return check;
        }
        if (source == 1) {
            int i = this.nonPermit(classesId, memberIds);
            //1付费 //2免费报名
            if (i==1||i==2) {
                Map<String, Object> map = new HashMap<>();
                map.put("status",i);
                return ResultUtil.ERROR("未购买班级课程",map);
            }
            if (i==4){
                Map<String, Object> map = new HashMap<>();
                map.put("status",i);
                return ResultUtil.ERROR("所在课程班级的课程已被删除",map);
            }
        }
        return classesMemberBiz.saveClassesMemberBatch(classesId, memberIds, identity, source);
    }

    private int nonPermit(BigDecimal classesId, String memberIds) {
        //1免费 //2付费 //3.可加入//4.班级课程删除
        if (StringUtils.isNumber(memberIds)) {
            Classes classes = classesBiz.findById(classesId);
            if (classes.isFree()) {
                return 3;
            }
            BigDecimal userId = new BigDecimal(memberIds);
            CourseBuyRecord record = courseBuyRecordBiz.checkUserBuyCourse(userId, classes.getCourseId());
            if(ObjectUtils.isEmpty(record)){
                Course course = CourseBiz.findCourseById(classes.getCourseId(),userId,true,true,false,false,false,false,false);
                if (StringUtils.isEmpty(course)){
                    return 4;
                }
                Map<String, Object> courseBuyStatus = course.getCourseBuyStatus();
                boolean freePriceBut = Boolean.parseBoolean(courseBuyStatus.get("freePriceBut").toString());
                if(freePriceBut){
                    return  1;
                }else{
                    return  2;
                }
            }else{
                boolean b = Objects.isNull(record) || record.getValidTime().before(new Date());
                if (b) {
                    return 2 ;
                }else{
                    return  3;
                }
            }
        }
        return 1;
    }

    /**
     * 更新班级成员状态
     *
     * @param ids    班级成员id
     * @param status 1.正常 2.封禁
     * @return 操作结果
     */
    @RequestMapping("/updateClassesMemberStatus")
    public Map<String, Object> updateClassesMemberStatus(@RequestParam("ids") String ids,
                                                         @RequestParam("status") Integer status) {
        ids = DataUtil.filterNotNumberStr(ids);
        if (StringUtils.isNotEmpty(ids)) {
            return classesMemberBiz.updateClassesMemberStatus(ids, status);
        }
        return ResultUtil.ERROR("选择操作的班级成员");
    }

    /**
     * 更新班级成员身份
     *
     * @param ids      班级成员id
     * @param identity 1.普通学员 2.班级管理员 3.班主任
     * @return 操作结果
     */
    @RequestMapping("/updateClassesMemberIdentity")
    public Map<String, Object> updateClassesMemberIdentity(@RequestParam("ids") String ids,
                                                           @RequestParam("identity") Integer identity) {
        ids = DataUtil.filterNotNumberStr(ids);
        if (StringUtils.isNotEmpty(ids)) {
            return classesMemberBiz.updateClassesMemberIdentity(ids, identity);
        }
        return ResultUtil.ERROR("选择操作的班级成员");
    }

    /**
     * 检测用户是否有购买，且未加入的班级
     * @param userId 用户ID
     * @return true有，false没有
     */
    @RequestMapping("/checkNoJoinClassesMember")
    public boolean checkNoJoinClassesMember(@RequestParam("userId") BigDecimal userId){
        return classesMemberBiz.checkNoJoinClassesMember(userId);
    }

    /**
     * 检查参数
     *
     * @param classesId 班级id
     * @param memberIds 成员id
     */
    private Map<String, Object> checkRequestParams(BigDecimal classesId, String memberIds) {
        if (!DataUtil.idIsNotNull(classesId)) {
            return ResultUtil.ERROR("选择班级");
        }
        memberIds = DataUtil.filterNotNumberStr(memberIds);
        if (StringUtils.isEmpty(memberIds)) {
            return ResultUtil.ERROR("没有选择成员");
        }
        return null;
    }


    /**
     * 删除班主任
     *
     * @param id      班级成员id
     */
    @RequestMapping("/deleteClassTeacher")
    Map<String, Object> deleteClassTeacher(@RequestParam("id") BigDecimal id){
        classesMemberBiz.deleteClassTeacher(id);
        return  ResultUtil.SUCCESS("删除成功");
    }
}
